package cn.edu.seig.textbook.utils;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Set;

/**
 * @author lenovo
 */
@Component
public class LoginSuccessHandle implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        Set<String> roles= AuthorityUtils.authorityListToSet(authentication.getAuthorities());
        String path=request.getContextPath();
        String basePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
        String realpath = "";
        System.out.println(basePath+roles);
        if (roles.contains("ROLE_admin")) {
            realpath = basePath + "admin/toAdmin";
            response.sendRedirect(realpath);
        } else if(roles.contains("ROLE_teacher")) {
            realpath = basePath + "teacher/toTeacher";
            response.sendRedirect(realpath);
        }else if(roles.contains("ROLE_finance")) {
            realpath = basePath + "purchase/toPurchase";
            response.sendRedirect(realpath);
        }else if(roles.contains("ROLE_student")) {
            realpath = basePath + "student/toStudent";
            response.sendRedirect(realpath);
        }else if(roles.contains("ROLE_admin")) {
            realpath = basePath + "admin/toAdmin";
            response.sendRedirect(realpath);
        }
        System.out.println("realpath=="+realpath);
    }
}
